<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" width="800"
             :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()"
             label-width="120px">
      <el-form-item label="状态" prop="foodStatus">
        <el-select v-model="dataForm.foodStatus" placeholder="状态 0-不可用 1-可用" style="width: 400px">
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="时段" prop="planDayTime">
        <el-select v-model="dataForm.planDayTime" filterable placeholder="适用时段" style="width: 400px">
          <el-option
            v-for="item in planDayTimeOpt"
            :key="item.key"
            :label="item.value"
            :value="item.key"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="起始bmi" prop="startBmi">
        <el-input type="number" v-model="dataForm.startBmi" placeholder="起始bmi" style="width: 400px"></el-input>
      </el-form-item>
      <el-form-item label="结束bmi" prop="endBmi">
        <el-input  type="number" v-model="dataForm.endBmi" placeholder="结束bmi" style="width: 400px"></el-input>
      </el-form-item>
    </el-form>

    <div>
      <h3>添加食物</h3>
      <el-form :model="planFood" ref="foodsRef" :rules="planRules" style="margin-left: 0" label-width="120px">
        <el-form-item label="食物名称" prop="foodId">
          <el-select v-model="planFood.foodId" placeholder="食物名称" style="width: 240px">
            <el-option
              v-for="item in foodOpt"
              :key="item.id"
              :label="item.foodName"
              :value="item.id"
            />
          </el-select>
          <span style="color: red;margin-left: 20px;" v-show="foodSelectText.weight">重量：{{foodSelectText.weight}}，热量：{{foodSelectText.trophy}}</span>
        </el-form-item>
        <el-form-item label="食物重量(克)" prop="foodWeight">
          <el-input type="number" v-model="planFood.foodWeight" placeholder="食物重量(克)" style="width: 400px"></el-input>
        </el-form-item>
        <el-form-item label="热量(大卡)" prop="trophy">
          <el-input type="number" v-model="planFood.trophy" placeholder="热量(大卡)" style="width: 400px"></el-input>
          <el-button type="primary" @click="addFoods" style="margin-left: 20px;">添加</el-button>
        </el-form-item>
      </el-form>

      <el-table v-if="dataForm.foodPrePlanDetails && dataForm.foodPrePlanDetails.length > 0" :data="dataForm.foodPrePlanDetails" stripe style="width: 100%">
        <el-table-column prop="foodName" label="食物名称" width="180"/>
        <el-table-column prop="foodWeight" label="食物重量(克)" width="180"/>
        <el-table-column prop="trophy" label="热量(大卡)"/>
      </el-table>
    </div>
    <el-divider/>

    <template #footer>
      <div style="width: 350px">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {reactive, ref, watchEffect} from "vue";
import baseService from "@/service/baseService";
import {ElMessage} from "element-plus";

const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();
const foodsRef = ref();
const planFood = ref({});
const foodSelectText = ref({weight:'',trophy:''});
const foodOpt = ref<Array<object>>([{}]);

const dataForm = reactive({
  id: '',
  foodStatus: '',
  planDayTime: '',
  startBmi: '',
  endBmi: '',
  deleted: '',
  createDate: '',
  creator: '',
  updateDate: '',
  updater: '',
  foodPrePlanDetails: [{}]
});

const planDayTimeOpt = ref([{key: '1', value: '早'}, {key: '2', value: '中'}, {key: '3', value: '晚'}])
const statusOptions = [
  {
    value: 1,
    label: '可用',
  },
  {
    value: 0,
    label: '不可用',
  }]
const rules = ref({
  foodStatus: [
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
  planDayTime: [
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
  startBmi: [
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
  endBmi: [
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
  deleted: [
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
});
const planRules = ref({
  foodId:[
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
  foodWeight:[
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
  trophy:[
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
})

const init = (id?: number) => {
  visible.value = true;
  dataForm.id = "";
  if(dataForm.foodPrePlanDetails) dataForm.foodPrePlanDetails.splice(0,dataForm.foodPrePlanDetails.length)
  foodSelectText.value = {weight:'',trophy:''};
  if (dataFormRef.value)foodsRef.value.resetFields()
  // 请求食物列表
  baseService.get("/health/food/page?order=&orderField=&page=1&limit=10000").then((res) => {
    foodOpt.value = res.data.list
  })

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  if (id) {
    getInfo(id);
  }
};

// 获取信息
const getInfo = (id: number) => {
  baseService.get("/health/foodpreplan/" + id).then((res) => {
    Object.assign(dataForm, res.data);
  });
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    (!dataForm.id ? baseService.post : baseService.put)("/health/foodpreplan", dataForm).then((res) => {
      ElMessage.success({
        message: '成功',
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};


const addFoods = () => {
  foodsRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    let food = foodOpt.value?.find(f => f.id == planFood.value.foodId);
    if (food) planFood.value.foodName = food.foodName
    dataForm.foodPrePlanDetails.push(JSON.parse(JSON.stringify(planFood.value)))
    planFood.value ={}
  });
}

watchEffect(() => {
  let food = foodOpt.value.find(food => planFood.value.foodId == food.id);
  if (food) {
    foodSelectText.value.weight = food.weight
    foodSelectText.value.trophy = food.foodTrophy
  }

})

defineExpose({
  init
});
</script>
